# coding=utf-8

import datetime
import random
import logging
from flask import render_template, request, abort, session, g, redirect, url_for
from flask_login import login_required
from over.handlers.my import mod
from over.model import Product, Order, db, OrderItem, CartItem, Server
from over.handlers.router import Router
from over.handlers.helper import jsonify, new_order_number
from .forms import OrderForm

logger = logging.getLogger('my.order')
router = Router()

PER_PAGE = 15


@router('/order')
class OrderRouter(object):
    __router_name__ = 'order'

    @router('/')
    def index(self):
        orders = Order.get_orders(g.user.id)
        return render_template('my/order/index.html', orders=orders)

    @router('/add', methods=['POST'])
    def new(self):
        cart_items = CartItem.get_items(g.user.id)

        # 将这些内容,放到订单中,然后可以请求支付
        order_num = Order.new_order_num()

        price = []
        for item in cart_items:
            item.is_deleted = True
            db.session.add(item)

            order_item = OrderItem(order_num=order_num, title=item.title, price=item.price, period=item.period,
                                   description=item.description, count=1)
            db.session.add(order_item)

            price.append(item.price)

        price = sum(price)
        order = Order(order_num=order_num, price=price, user_id=g.user.id)
        db.session.add(order)

        db.session.commit()

        return redirect(url_for('over.handlers.my.order.list'), code=301)

    @router('/list', methods=['GET'])
    def list(self):
        orders = Order.get_orders(g.user.id)
        return render_template('my/order/list.html', orders=orders)

    @router('/cancel', methods=['POST'])
    def cancel(self):
        order_num = request.form.get('orderNum')
        if Order.cancel(order_num):
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': u'无效的订单号'})

    @router('/pay', methods=['POST'])
    def pay(self):
        order_num = request.form.get('orderNum')
        order = Order.get_order(order_num)
        if order is None:
            return jsonify({'success': False, 'error': u'无效的订单号'})

        if g.user.balance < order.price:
            return jsonify({'success': False, 'error': u'余额不足,请先充值'})

        order.status = 1
        if not g.user.pay(order.price):
            return jsonify({'success': False, 'error': u'支付失败'})

        db.session.add(g.user)

        order.status = 2
        db.session.add(order)

        # 生成过期时间
        expire = order.account_expire()
        server = Server.user_random(g.user)
        account = g.user.new_account(expire, server)
        account.status = 1
        db.session.add(account)

        # TODO: 最好是开启线程进行支付
        result = server.remote_notify(account)
        logger.info('remote server result {0}'.format(result))

        db.session.commit()

        return jsonify({'success': True})


router.register_url_rules(mod)
